package com.net.core.core.sql;
import com.net.core.core.reuslt.MyPage;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;

public class PageUtils {

    private MyPage myPage;
    private YxSqlPlus sql;
    private YxSql countSql;


    //    开始位置
    private long endIndex;

    public PageUtils(YxSqlPlus sql, MyPage page) {
        this.sql = sql;
        countSql = new YxSql();
        this.myPage = page;
        if (page.getCurrent() < 1) {
            page.setCurrent(1);
        }
        endIndex = page.getCurrent() * page.getSize();
    }

    public void setPage(MyPage page) {
        this.myPage = page;
    }

    public MyPage getPage() {
        return this.myPage;
    }


    /**
     * 前置sql
     *
     * @param sqlStr
     * @return
     */
    private String getPreSql(String sqlStr) {
        String[] froms = sqlStr.toLowerCase().split(" from");
        String select = froms[0];
        StringBuilder sb = new StringBuilder();
        if (!select.toLowerCase().contains(myPage.getSortKey().toLowerCase())) {
            select += "," + myPage.getSortKey();
        }
        sb.append(select).append(" from ").append(sql.getTableName());
        return sb.toString();
    }

    /**
     * 后置sql
     *
     * @param sqlStr
     * @return
     */
    private String getAfterSql(String sqlStr, String keys) {
        String where = " ";
        String tempS = sqlStr.toLowerCase();
        if (tempS.contains("union")) {
            where = tempS.substring(tempS.indexOf(" where"), tempS.indexOf("union"));
        } else if (sqlStr.contains("where")) {
            where = tempS.substring(tempS.indexOf(" where"));
        }

        if (!keys.contains(myPage.getSortKey())) {
            keys = keys + "," + myPage.getSortKey();
        }

        StringBuilder sb = new StringBuilder();
        sb.append("SELECT ").append(keys).append(" FROM ").append(sql.getTableName()).append(where);
        return sb.toString();
    }

    private String getKey() {
        Map<String, Field> tablePrimaryKey = sql.getTablePrimaryKey();
        Iterator<String> iterator = tablePrimaryKey.keySet().iterator();
        String keys = "";
        while (iterator.hasNext()) {
            keys += iterator.next();
            if (iterator.hasNext()) {
                keys += ",";
            }
        }
        return keys;
    }

    private String getOrderBy(boolean invert) {
        int sortType = myPage.getSortType();
        boolean isDESC = sortType == 1;
        isDESC = invert ? isDESC : !isDESC;
        return isDESC ? " DESC " : " ASC ";
    }

    private String getWheres() {
        Map<String, Field> tableIds = sql.getTableIds();
        Iterator<Field> iterator = tableIds.values().iterator();
        StringBuilder wheres = new StringBuilder(" WHERE ");
        while (iterator.hasNext()) {
            Field next = iterator.next();
            wheres.append(" w1.").append(next.getName()).append("=").append("w2.").append(next.getName());
            if (iterator.hasNext()) {
                wheres.append(" and ");
            }
        }
        return wheres.toString();
    }

    private String orderBy(String tableName, boolean isInvert) {
        StringBuilder order = new StringBuilder(" ORDER BY ");
        if (myPage.getSortKey().trim().length() > 0) {
            order.append(tableName).append(myPage.getSortKey()).append(getOrderBy(isInvert));
        } else {
            Map<String, Field> tableIds = sql.getTableIds();
            Iterator<Field> iterator = tableIds.values().iterator();
            while (iterator.hasNext()) {
                Field next = iterator.next();
                order.append(tableName).append(next.getName()).append(getOrderBy(isInvert));
                if (iterator.hasNext()) {
                    order.append(",");
                }
            }
        }
        return order.toString();
    }

    public String toSql() {
        String sqlStr = sql.toSql();
        String keys = getKey();
        if(myPage.getSortKey()==null) myPage.setSortKey(keys);
        String preSql = getPreSql(sqlStr);
        String afterSql = getAfterSql(sqlStr, keys);
        long size = myPage.getSize();
        StringBuffer sb = new StringBuffer();
        if (myPage.getSortKey() == null) myPage.setSortKey(keys);
        sb.append("SELECT * FROM (").append(preSql).append(") w1,(select TOP ")
                .append(size).append(" * ").append("from( select TOP ").append(endIndex).append(" * ")
                .append(" from ( ").append(afterSql).append(" ) temp ").append(orderBy("temp.", true))
                .append(" ) temp1 ").append(orderBy("temp1.", false))
                .append(" ) as w2 ").append(getWheres()).append(orderBy("w1.", true));
        return sb.toString();
    }

    public String getCountSql() {
        String sqls = sql.sql.toString().toLowerCase();
        String form = sqls.substring(sqls.indexOf("from"));
        sqls = "select year_flag_ as tableName ,count(*) as total " + form;

        String tableName = sql.getTableName();
        String replace = sqls.toLowerCase().replace(tableName.toLowerCase(), sql.getTableName());
        replace = replace.replace("year_flag_", "'" + sql.getTableName()+ "'");
        countSql.append(replace);
        countSql.addValue(sql.getValueList());
        return countSql.toSql();
    }

}
